<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="lib/vue.js"></script>
</head>

<body>
    <div id="app">
        <div>父组件</div>

        <div>
            <button @click='handle'>销毁事件</button>
        </div>
        <test-tom></test-tom>

        <test-jerry></test-jerry>
    </div>


    <script>
        /**
         * 兄弟组件之间传递数据
         */

        //提供事件中心
        var hub = new Vue();

        Vue.component('test-tom', {
            data() {
                return {
                    num: 0
                }
            },
            template: `
            <div>
                <div>Tom: {{num}}</div>
                <div>
                    <button @click='handle'>点击</button>
                </div>
            </>
        `,
            methods: {
                handle() {
                    hub.$emit('jerry-event', 1);
                }
            },
            //在mounted生命周期函数中监听事件
            mounted() {
                hub.$on('tom-event', (val) => {
                    this.num += val;
                });
            }
        })

        Vue.component('test-jerry', {
            data() {
                return {
                    num: 0
                }
            },
            template: `
            <div>
                <div>Jerry: {{num}}</div>
                <div>
                    <button @click='handle'>点击</button>
                </div>
            </>
        `,
            methods: {
                handle() {
                    hub.$emit('tom-event', 2);
                }
            },
            //在mounted生命周期函数中监听事件
            mounted() {
                hub.$on('jerry-event', (val) => {
                    this.num += val;
                });
            }
        })
        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {
                handle() {
                    hub.$off('tom-event')
                    hub.$off('jerry-event')
                }
            }
        });
    </script>
</body>

</html>